package com.fourforfo.fourmall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: xxl-sso-core
 * @description: 库存回滚的相关交换机，队列配置
 * @author: fourforfo
 * @email: fourforfo@gmail.com
 * @create: 2022-09-11 10:29
 **/
@Configuration
public class WareRollbackMQConfig {


    //延迟队列名
    public static String STOCK_LOCKED_QUEUE ="stock.locked.queue";
    //订单释放队列名
    public static String STOCK_RELEASE_QUEUE="stock.release.queue";
    //交换机名字
    public static String STOCK_EVENT_EXCHANGE="stock-event-exchange";
    //订单延迟路由
    public static String STOCK_LOCKED_ROUTE ="stock.locked";
    //订单释放路由
    public static String STOCK_RELEASE_ROUTE ="stock.release.#";

    /**
     * 交换机，根据路由确定消息转发到哪个队列
     * @return
     */
    @Bean
    public Exchange stockEventExchange(){
        //String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
        return new TopicExchange(STOCK_EVENT_EXCHANGE,true,false);
    }

    /**
     * 带过期时间的队列，等时间一到，就将消息转发到死信队列中
     *  不能被任何服务监听，由消息自动过期
     * @return
     */
    @Bean
    public Queue stockDelayQueue(){
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        /*
        arguments:
            x-dead-letter-exchange: stock-event-exchange
            x-dead-letter-routing-key: stock.release.stock
            x-message-ttl: 60000
         */
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","stock-event-exchange");
        arguments.put("x-dead-letter-routing-key","stock.release");
        arguments.put("x-message-ttl",90000);//ttl以毫秒为单位，此处表示90s，该时间需要略大于订单自动过期时间
        return new Queue(STOCK_LOCKED_QUEUE,true,false,false,arguments);
    }

    /**
     * 延迟队列
     * @return
     */
    @Bean
    public Queue stockReleaseQueue(){
        //设置延迟队列为stock.release.queue
        return new Queue(STOCK_RELEASE_QUEUE,true,false,false);
    }

    @Bean
    public Binding stockLockedBinding(){
        /**
         * String destination,
         * DestinationType destinationType,
         * String exchange,
         * String routingKey,
         * Map<String, Object> arguments
         */
        return new Binding(STOCK_LOCKED_QUEUE,Binding.DestinationType.QUEUE,STOCK_EVENT_EXCHANGE, STOCK_LOCKED_ROUTE,null);
    }

    @Bean
    public Binding stockReleaseBinding(){
        return new Binding(STOCK_RELEASE_QUEUE,Binding.DestinationType.QUEUE,STOCK_EVENT_EXCHANGE, STOCK_RELEASE_ROUTE,null);
    }

}
